package xing.application.service.isv.suite;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xing.application.api.DingApi;
import xing.application.service.BaseService;
import xing.domain.isv.suite.QSuiteTicket;
import xing.domain.isv.suite.Suite;
import xing.domain.isv.suite.SuiteTicket;
import xing.infrastructure.data.CallResult;
import xing.infrastructure.util.IdWorker;
import xing.repository.isv.suite.SuiteRepository;
import xing.repository.isv.suite.SuiteTicketRepository;

import java.util.Calendar;
import java.util.Date;

/********************************
 * 文 件 名 :SuiteTicketService.java
 * 创 建 人：陈天龙
 * 日    期：2017/8/22
 * 描   述：套件ticket业务处理类
 * 版 本 号：v1.0.0
 ********************************/
@Service
public class SuiteTicketService extends BaseService{

    @Autowired
    private SuiteTicketRepository suiteTicketRepository;
    @Autowired
    private SuiteRepository suiteRepository;
    @Autowired
    private DingApi dingApi;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 描    述：新增套件ticket
     * 创 建 人：陈天龙
     * 日    期：2017/8/22
     * @param suiteKey
     * @param ticket
     * @return CallResult
     */
    @Transactional(rollbackFor = Exception.class)
    public CallResult saveOrUpdateSuiteTicket(String suiteKey,String ticket)throws Exception{
        Date now = new Date();
        SuiteTicket suiteTicket = new SuiteTicket();
        Suite suite = suiteRepository.findBySuiteKey(suiteKey);
        //获取到suiteTicket之后需要换取suiteToken
        String suiteTokenJson = dingApi.getSuiteToken(suiteKey,suite.getSuiteSecret(),ticket);
        logger.info("获取suiteToken的数据:"+suiteTokenJson);
        JSONObject suiteToken = JSONObject.parseObject(suiteTokenJson);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.SECOND,suiteToken.getInteger("expires_in"));
        SuiteTicket suiteTicketEx = new SuiteTicket();
        suiteTicketEx.setSuiteKey(suiteKey);
        QSuiteTicket qSuiteTicket = QSuiteTicket.suiteTicket;
        if(null==suiteTicketRepository.findOne(Example.of(suiteTicketEx, ExampleMatcher.matching()))){
            suiteTicket.setId(IdWorker.nextId());
            suiteTicket.setGmtCreate(now);
            suiteTicket.setGmtModified(now);
            suiteTicket.setSuiteKey(suiteKey);
            suiteTicket.setTicket(ticket);
            suiteTicket.setSuiteToken(suiteToken.getString("suite_access_token"));
            suiteTicket.setExpiredTime(calendar.getTime());
            suiteTicketRepository.save(suiteTicket);
        }else{
            queryFactory.update(qSuiteTicket)
                    .where(qSuiteTicket.suiteKey.stringValue().eq(suiteKey))
                    .set(qSuiteTicket.gmtModified,now)
                    .set(qSuiteTicket.ticket,ticket)
                    .set(qSuiteTicket.suiteToken,suiteToken.getString("suite_access_token"))
                    .set(qSuiteTicket.expiredTime,calendar.getTime())
                    .execute();
        }

        return CallResult.ok();
    }
}
